package com.paradogs.gs.modules.role;

import com.paradogs.common.utils.JwtUtils;
import com.paradogs.framework.annotations.serverHandler.PRHandleBefore;
import com.paradogs.framework.annotations.serverHandler.PRHandler;
import com.paradogs.framework.annotations.serverHandler.PRMapping;
import com.paradogs.framework.misc.Ack;
import com.paradogs.framework.misc.GC;
import com.paradogs.framework.server.ParadogsContext;
import com.paradogs.gs.db.Role;
import com.paradogs.gs.misc.Bow;
import com.paradogs.gs.modules.role.dao.RoleDao;
import com.paradogs.gs.modules.role.msg.CGInitRole;
import com.paradogs.gs.modules.role.msg.CGLogin;
import com.paradogs.gs.modules.Player;
import com.paradogs.gs.utils.PlayerUtils;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author: yumi
 * @date: 2024/10/23  23:02
 * @Description: TODO
 */
@Slf4j
@PRHandler
@PRMapping("role")
public class RoleHandler {

    @Autowired
    private RoleDao roleDao;

    @PRHandleBefore("role.login")
    public void loginBefore(CGLogin cg, Channel channel) {
        // 验证 jwt
        Bow.asserts(JwtUtils.verifyToken(cg.getToken()));
        Long uid = JwtUtils.getUserId(cg.getToken());
        // 设置 Actor 队列 id
        channel.attr(AttributeKey.valueOf("actor_id")).set(uid.toString());
    }

    // 如果 return false 则需要创建角色再 login
    @PRMapping("login")
    public GC<Ack> login(CGLogin cg, ParadogsContext ctx) {

        Bow.asserts(JwtUtils.verifyToken(cg.getToken()));
        Long uid = JwtUtils.getUserId(cg.getToken());

        // 踢掉上一位该账号连接 kick()
        Player oldPlayer = PlayerUtils.getPlayer(uid);
        if (oldPlayer != null && oldPlayer.online()) {
            oldPlayer.kick();
            log.info("玩家顶号，uid: {}", uid);
        }

        Player player = new Player(uid);
        player.StartBefore();

        PlayerUtils.setSession(ctx.getChannel(), player);
        player.Start();
        player.online(true);

        return GC.ok();
    }

    @PRMapping("logout")
    public void logout() {
        Bow.owner().kick();
    }

    @PRMapping("initRole")
    public GC<Ack> initRole(CGInitRole cg) {
        RoleMgr mgr = Bow.owner().roleMgr();
        Bow.asserts(mgr.__raw__().getInit() == false);
        Role role = mgr.__get__();
        role.setNickName(cg.getNickName());
        role.setSex(cg.getSex());
        role.setInit(true);
        mgr.__update__(role);
        return GC.ok();
    }

}
